var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
var lineObj = {};
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    $(".startTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    $(".endTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    // $(".update-today").datePicker({
    //     format:"YYYY-MM",
    //     singleDate:true,  //单选日期
    // });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgName', title: '公司', width: '15%', align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'lineName', title: '生产线名称', width: '15%', align: 'center',templet:function (val) {
                return lineObj[val.lineId];
            }}
            ,{field: 'name', title: '仓位名称', width: '10%', align: 'center'}
            ,{field: 'type', title: '仓位类型', width:'10%', align: 'center', templet:function (val) {
                if (val.type == 0)
                    return '筒仓';
                else
                    return '堆场';
            }}
            ,{field: 'materialName', title: '仓位材料名称', width: '15%', align: 'center'}
            ,{field: 'status', title: '状态', width:'5%', align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: '20%', align: 'center'}
            ,{fixed: 'right', title:'操作', width: '10%', align:'center', templet:function (val) {
                var str = '';
                // if (val.status == 0)
                //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                // else
                //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/control/storage/page'
        ,method: 'post'
        ,page: true
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    id: id,
                    status: updateStatus
                };
                save(option, "/control/storage/update-status");
            }, function(index){

            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $('.updateModal').show();
            $('.updateModal .update-origin').val(data.orgId);
            $('.updateModal .update-line').val(loadLineList({lineId:data.lineId}));
            $('.updateModal .update-name').val(data.name);
            $('.updateModal .update-type').val(data.type);
            $('.updateModal .update-materialName').val(data.materialName);
            $('.updateModal .remark').val(data.remark);
            form.render();
        }
    });

    // form.on('select(search-today)', function(data) {
    //     $(".btn-query").trigger("click");
    // });
    form.on('select(search-sysLine)', function(data) {
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var lineId = $('.search-sysLine').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(lineId))
            option['lineId'] = lineId;
        table.reload('body-list', {
            where: option
        });
    });

    $('.btn-add').on('click', function () {
        loadLineList({});
        $('.addModal').show();
    });
    $('.btn-refund').on('click', function () {
        $('.refundModal').show();
    });
    $(".addModal .close").on("click", function() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });
    $(".updateModal .close").on("click", function() {
        $(".updateModal").hide();
        $(".updateModal input").val("");
        $(".updateModal select").val("");
        $(".updateModal textarea").val("");
        form.render();
        tid = -1;
    });
    form.on('submit(updateBtns)', function() {
        var orgId = $.trim($(".updateModal .update-origin").val());//公司
        var remark = $.trim($(".updateModal .update-remark").val());//备注
        var lineId = $.trim($(".updateModal .update-line").val());//生产线
        var name = $.trim($(".updateModal .update-name").val());//仓位名称
        var type = $.trim($(".updateModal .update-type").val());//类型
        var materialName = $.trim($(".updateModal .update-materialName").val());//仓位材料名称
        var options = '{"id":'+tid+',"orgId":'+orgId+',"remark":"'+remark+'","lineId":'+lineId+',"name":"'+name+'","type":'+type+',"materialName":"'+materialName+'"}';
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        saveJson(options, "/control/storage/update");
    });

    //点击添加提交
    form.on('submit(addBtns)', function() {
        var orgId = $.trim($(".addModal .add-origin").val());//公司
        var remark = $.trim($(".addModal .remark").val());//备注
        var lineId = $.trim($(".addModal .add-line").val());//生产线
        var name = $.trim($(".addModal .add-name").val());//仓位名称
        var type = $.trim($(".addModal .add-type").val());//类型
        var materialName = $.trim($(".addModal .add-materialName").val());//仓位材料名称
        var options = '{"orgId":'+orgId+',"remark":"'+remark+'","lineId":'+lineId+',"name":"'+name+'","type":'+type+',"materialName":"'+materialName+'"}';
        saveJson(options, "/control/storage/save");
    });

    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("更新成功!");
                    table.reload('body-list', { where: {offset: 0,page:1,
                            limit: limit,
                            lineId:$('.search-sysLine').val(),
                            searchVal:$('.search-text').val()} });
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    $(".updateModal").hide();
                    $(".updateModal input").val("");
                    $(".updateModal select").val("");
                    $(".updateModal textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    function saveJson(option, url) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("更新成功!");
                    table.reload('body-list', { where: {offset: 0,page:1,
                            limit: limit,
                            lineId:$('.search-sysLine').val(),
                            searchVal:$('.search-text').val()} });
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    $(".updateModal").hide();
                    $(".updateModal input").val("");
                    $(".updateModal select").val("");
                    $(".updateModal textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    /**
     * 初始化查询下拉框
     */
    loadInitLineList();
    function loadInitLineList() {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/sysLine/find-all',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: {},
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择生产线</option>';
                    $.each(data, function (i, v) {
                        lineObj[v.id] = v.name;
                        html += '<option value="' + v.id + '">' + v.code + '[' + v.name + ']' + '</option>';
                    });
                    $('.search-sysLine').html(html);
                } else {
                    $('.search-sysLine').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    //根据公司标识查询生产线数据
    function loadLineList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/system/sysLine/find-all',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择生产线</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.code + '[' + v.name + ']' + '</option>';
                    });
                    $('.add-line').html(html);
                    $('.update-line').html(html);
                } else {
                    $('.add-line').html('<option value="">暂无数据</option>');
                    $('.update-line').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.lineId)) {
                    $('.update-line').val(obj.lineId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

});